package com.bsi.core.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;


public class DateUtils extends org.apache.commons.lang.time.DateUtils {
	public static Log log = LogFactory.getLog(DateUtils.class);
	public static String timePattern = "yyyy-MM-dd HH:mm";
	public static String defaultDateDB = "yyyy-MM-dd";
	public static String cnDateDB = "yyyy年MM月dd日";
	public static String timesecondPattern = "yyyy-MM-dd HH:mm:ss";
	public static String timesecondPatterns = "yyyyMMddHHmmsss";
	public static String shortPattern = "yyyy-MM";

	@SuppressWarnings("deprecation")
	public static String getCurrentYear1stDay(String currentDate) {
		Date date = Timestamp.valueOf(currentDate + " 00:00:01.0");
		return (1900 + date.getYear()) + "-01-01";
	}

	@SuppressWarnings("deprecation")
	public static String getCurrentMonth1stDay(String currentDate) {
		Date date = Timestamp.valueOf(currentDate + " 00:00:01.0");
		return (1900 + date.getYear()) + "-" + (1 + date.getMonth()) + "-1";
	}

	/**
	 * 得到给定日期的上一年最后一天
	 * 
	 * @param currentDate
	 *            : yyyy-MM-dd
	 * @author koudepei
	 */
	public static String getLastDayOfLastYear(String currentDate) {
		Date date = Timestamp.valueOf(currentDate + " 00:00:01.0");
		return (1900 + date.getYear() - 1) + "-12-31";
	}

	/**
	 * 得到当前日期的前几天
	 * 
	 * @param days
	 * @author shandabin
	 */
	@SuppressWarnings("deprecation")
	public static String getYesterday(int days) {
		String currentDate = getCurrentDate("yyyy-MM-dd");
		Date date = Timestamp.valueOf(currentDate + " 00:00:01.0");
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		int day = calendar.get(Calendar.DATE);
		calendar.set(Calendar.DATE, day - days);
		Date ddd = calendar.getTime();
		return (1900 + ddd.getYear()) + "-" + (1 + ddd.getMonth()) + "-" + ddd.getDate();
	}

	/**
	 * 得到给定日期的前几天
	 * 
	 * @param currentDate
	 *            : yyyy-MM-dd
	 * @param days
	 * @author shandabin
	 */
	@SuppressWarnings("deprecation")
	public static String getYesterday(String currentDate, int days) {
		Date date = Timestamp.valueOf(currentDate + " 00:00:01.0");
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		int day = calendar.get(Calendar.DATE);
		calendar.set(Calendar.DATE, day - days);
		Date ddd = calendar.getTime();
		return (1900 + ddd.getYear()) + "-" + (1 + ddd.getMonth()) + "-" + ddd.getDate();
	}

	// 取得当前日期的前几天
	public static Date getBeforDate(Date date, int days) {
		date = date == null ? new Date() : date;
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		int day = calendar.get(Calendar.DATE);
		calendar.set(Calendar.DATE, day - days);
		return calendar.getTime();
	}
	public static String getYesterdayCG(String currentDate, int days) {
		Date date = Timestamp.valueOf(currentDate + " 00:00:01.0");
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		int day = calendar.get(Calendar.DATE);
		calendar.set(Calendar.DATE, day - days);
		Date ddd = calendar.getTime();
		return (1900 + ddd.getYear()) + "-" + (1 + ddd.getMonth() < 10 ? "0" + (1 + ddd.getMonth()) : (1 + ddd.getMonth())) + "-"
				+ (ddd.getDate() < 10 ? "0" + ddd.getDate() : ddd.getDate());
	}

	/**
	 * 得到给定日期的前一天
	 * 
	 * @param currentDate
	 *            : yyyy-MM-dd
	 * @author koudepei
	 */
	@SuppressWarnings("deprecation")
	public static String getYesterday(String currentDate) {
		Date date = Timestamp.valueOf(currentDate + " 00:00:01.0");
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		int day = calendar.get(Calendar.DATE);
		calendar.set(Calendar.DATE, day - 1);
		Date ddd = calendar.getTime();
		return (1900 + ddd.getYear()) + "-" + (1 + ddd.getMonth()) + "-" + ddd.getDate();
	}

	public static String getYesterday() {
		Date pre_date = new Date(System.currentTimeMillis() - 1 * 24 * 3600 * 1000);

		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

		return formatter.format(pre_date);
	}

	/**
	 * 得到当前年
	 *
	 * @param currentDate
	 * @return String
	 * @author zhao
	 * @updateDate 2008-06-24
	 */
	@SuppressWarnings("deprecation")
	public static int getCurrentYear(String currentDate) {

		Date date = Timestamp.valueOf(currentDate + " 00:00:01.0");
		return 1900 + date.getYear();

	}

	/**
	 * 得到当前年
	 *
	 * @return
	 * @author EXvision
	 * @since 2008-6-25
	 */
	public static int getCurrentYear() {
		return Calendar.getInstance().get(Calendar.YEAR);
	}

	/**
	 * 得到当前月
	 *
	 * @return
	 * @author EXvision
	 * @since 2008-6-25
	 */
	public static int getCurrentMonth() {
		return (Calendar.getInstance().get(Calendar.MONTH) + 1);
	}

	/**
	 * 得到当前月
	 *
	 * @param currentDate
	 * @return String
	 * @author zhao
	 * @updateDate 2008-06-24
	 */
	@SuppressWarnings("deprecation")
	public static int getCurrentMonth(String currentDate) {

		Date date = Timestamp.valueOf(currentDate + " 00:00:01.0");
		return 1 + date.getMonth();

	}

	/**
	 * 比较字符串日期大小(格式yyyy-MM-dd)
	 *
	 * @param startDate
	 * @param endDate
	 * @param dateFormat
	 *            时间格式 例:yyyy-MM-dd yyyyMMdd
	 * @return int - 1 开始时间小于结束时间 0 开始时间小于结束时间 1 开始时间等于结束时间
	 * @author zhao
	 * @since 2008-07-25
	 */
	public static int dateCompare(String startDate, String endDate, String dateFormat) {

		SimpleDateFormat format = new SimpleDateFormat(dateFormat);
		Date beforeDate = null;
		Date afterDate = null;

		try {
			beforeDate = format.parse(startDate);
			afterDate = format.parse(endDate);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			return -99;
		}

		return beforeDate.compareTo(afterDate);
	}

	/**
	 * 格式化日期字符串
	 *
	 * @param dateFormat
	 *            时间格式
	 * @return String
	 * @author zhao
	 * @since 2008-07-25
	 */
	public static String getFormatDate(Date date, String dateFormat) {
		if(null == date) {
			return "";
		}
		SimpleDateFormat format = new SimpleDateFormat(dateFormat);
		return format.format(date);
	}

	/**
	 * 取得中文日期格式
	 *
	 * @param date
	 * @return
	 */
	public static String getCnFormatDate(Date date) {
		if (date == null)
			date = new Date();
		SimpleDateFormat format = new SimpleDateFormat(cnDateDB);
		return format.format(date);
	}

	/**
	 * 格式化日期字符串
	 *
	 * @param dateFormat
	 *            时间格式
	 * @return String
	 * @author zhao
	 * @since 2008-07-25
	 */
	public static String getSimpleFormatDate(Date date) {
		if (date == null) {
			date = new Date();
		}
		SimpleDateFormat format = new SimpleDateFormat(defaultDateDB);
		return format.format(date);
	}

	/**
	 * Calendar,比较时间差
	 *
	 * @param oldCa
	 * @param newCa
	 * @return int
	 * @author zhao
	 * @since 2008-11-24
	 */
	public static int dateCompare(Calendar start, Calendar end) {

		long s = Math.abs(start.getTimeInMillis());
		long e = Math.abs(end.getTimeInMillis());

		return (int) ((s - e) / (1000 * 60 * 60 * 24));
	}

	public static int dateCompareCalendar(String startDate, String endDate, String dateFormat) {

		SimpleDateFormat format = new SimpleDateFormat(dateFormat);
		Date beforeDate = null;
		Date afterDate = null;
		int i = 0;
		try {
			beforeDate = format.parse(startDate);
			afterDate = format.parse(endDate);

			Calendar start = Calendar.getInstance();
			Calendar end = Calendar.getInstance();
			start.setTime(beforeDate);
			end.setTime(afterDate);
			i = dateCompare(start, end);

		} catch (ParseException e) {
			// TODO Auto-generated catch block
			return -99;
		}

		return i;
	}

	public static int getCurrentHour() {
		return Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
	}

	public static String getCurrentDay() {
		return String.valueOf(Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
	}

	public final static Date string2DateE(String dateString, String format) {
		if (null == dateString || dateString.equals(""))
			return null;
		Date date = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat(format);
		try {
			date = formatter.parse(dateString);
		} catch (Exception e) {
			return null;
		}
		return date;
	}

	/**
	 * 年初前一年12月31号
	 *
	 * @param model
	 *            date
	 * @return String
	 * @author wang
	 * @since 2008-12-30
	 */
	@SuppressWarnings("static-access")
	public static String beginYear(String d) {
		String year = "";
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
			Calendar cal = Calendar.getInstance();
			Date date = sdf.parse(d);
			cal.setTime(date);
			cal.add(cal.YEAR, -1);
			year = sdf.format(cal.getTime()) + "-12-31";
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return year;
	}

	// d:当前时间（yyyy）,num:前几年
	public static String beforYear(String d, int num) {
		String year = "";
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
			Calendar cal = Calendar.getInstance();
			Date date = sdf.parse(d);
			cal.setTime(date);
			cal.add(cal.YEAR, -num);
			year = sdf.format(cal.getTime());
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return year;
	}

	public static String afterYear(String d, int num) {
		String year = "";
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Calendar cal = Calendar.getInstance();
			Date date = sdf.parse(d);
			cal.setTime(date);
			cal.add(cal.YEAR, num);
			year = sdf.format(cal.getTime());
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return year;
	}

	/**
	 * 月初 上月月底
	 *
	 * @param model
	 *            date
	 * @return String
	 * @author wang
	 * @since 2008-12-30
	 */
	@SuppressWarnings("static-access")
	public static String beginMonth(String d) {
		String year = "";
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Calendar cal = Calendar.getInstance();
			Date date = sdf.parse(d);
			cal.setTime(date);
			cal.set(cal.DATE, 1);
			cal.add(cal.DATE, -1);
			year = sdf.format(cal.getTime());
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return year;
	}

	/**
	 * 取得当前日期前或后几天
	 *
	 * @param int
	 * @return String
	 * @author cgcg1981
	 * @since 2009-04-08
	 */
	public static String befourOrlaterDay(int day, String sformat) {
		Calendar cal = Calendar.getInstance();
		cal.add(cal.DATE, day);
		SimpleDateFormat format = new SimpleDateFormat(sformat);

		return format.format(cal.getTime());
	}

	/**
	 * 得到当前时间
	 *
	 * @param format
	 * @return string
	 * @author zhao
	 * @since 2009-06-17
	 */
	public static String getCurrentDate(String format) {

		Date date = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat();
		dateFormat.applyPattern(format);

		return dateFormat.format(date);
	}

	public static Date getCurrentForDate(String format) {

		String strDate = getCurrentDate(format);
		return string2DateE(strDate, format);
	}

	/**
	 * Calendar,比较时间差
	 *
	 * @param oldCa
	 * @param newCa
	 * @return int
	 * @author cg
	 * @since 2010-06-17
	 */
	public static int dateCompareMinute(String startdate, String enddate) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		long min = 0;
		try {
			Date start = dateFormat.parse(startdate);
			Date end = dateFormat.parse(enddate);
			long time = end.getTime() - start.getTime();

			long day = time / (24 * 60 * 60 * 1000);
			long hour = (time / (60 * 60 * 1000) - day * 24);
			min = ((time / (60 * 1000)) - day * 24 * 60 - hour * 60);

		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return (int) min;
	}

	/**
	 * 得到1991-11-11形式的日期
	 *
	 * @return
	 */
	public static Date getDate() {
		Date date = null;
		try {
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			date = dateFormat.parse(getFormatDate(new Date(), "yyyy-MM-dd"));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}

	/**
	 * 得到1991-11-11形式的日期
	 *
	 * @return
	 */
	public static Date getDate(Date date) {
		try {
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			date = dateFormat.parse(getFormatDate(date, "yyyy-MM-dd"));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}

	/**
	 * 得到电工证的有效日期
	 *
	 * @return
	 */
	public static Date getElecDate(Date date) {
		date = convertStringToDate(getYesterday(afterYear(getSimpleFormatDate(date), 3)));

		return date;
	}

	public static final String getDateTime(String aMask, Date aDate) {
		SimpleDateFormat df = null;
		String returnValue = "";

		if (aDate == null) {
			return returnValue;
		} else {
			df = new SimpleDateFormat(aMask);
			returnValue = df.format(aDate);
		}
		return returnValue;
	}

	/**
	 * 判断日期为星期几,7为星期六,依此类推
	 *
	 * @param dateStr
	 * @return
	 */
	public static String dayOfWeek(String dateStr) {
		Date date = DateUtils.convertStringToDate(dateStr);
		// 首先定义一个calendar，必须使用getInstance()进行实例化
		Calendar aCalendar = Calendar.getInstance();
		// 里面可以直接插入date类型
		aCalendar.setTime(date);
		// 计算此日期是一周中的哪一天
		int intDay = aCalendar.get(Calendar.DAY_OF_WEEK);
		String strDay = "";
		switch (intDay) {
		case 1:
			strDay = "日";
			break;
		case 2:
			strDay = "一";
			break;
		case 3:
			strDay = "二";
			break;
		case 4:
			strDay = "三";
			break;
		case 5:
			strDay = "四";
			break;
		case 6:
			strDay = "五";
			break;
		case 7:
			strDay = "六";
			break;
		}
		return strDay;
	}

	/**
	 * This method converts a String to a date using the datePattern
	 *
	 * @param strDate
	 *            the date to convert (in format yyyy-MM-dd HH:mm)
	 * @return a date object
	 *
	 * @throws ParseException
	 */
	public static Date convertStringToDate(String strDate) {
		Date aDate = null;
		try {
			if (log.isDebugEnabled())
				log.debug((new StringBuilder("converting date with pattern: ")).toString());
			if (strDate.length() == 7)
				aDate = convertStringToDate(shortPattern, strDate);
			if (strDate.indexOf("年") > -1 && strDate.indexOf("月") > -1 && strDate.indexOf("日") > -1)
				aDate = convertStringToDate(cnDateDB, strDate);
			else if (strDate.length() == 10)
				aDate = convertStringToDate(defaultDateDB, strDate);
			else if (strDate.length() == 9 || strDate.length() == 8)
				aDate = convertStringToDate(defaultDateDB, strDate);
			else if (strDate.length() == 16)
				aDate = convertStringToDate(timePattern, strDate);
			else if (strDate.length() == 19)
				aDate = convertStringToDate(timesecondPattern, strDate);
			if (strDate.length() == 21) {
				strDate = strDate.substring(0, 19);
				aDate = convertStringToDate(timesecondPattern, strDate);
			} else
				log.error((new StringBuilder()).append(aDate).append(" format incorrectness!").toString());
		} catch (ParseException pe) {
			log.error((new StringBuilder("Could not convert '")).append(strDate).append("' to a date, throwing exception").toString());
			pe.printStackTrace();
		}
		return aDate;
	}

	/**
	 * This method generates a string representation of a date/time in the
	 * format you specify on input
	 *
	 * @param aMask
	 *            the date pattern the string is in
	 * @param strDate
	 *            a string representation of a date
	 * @return a converted Date object
	 * @see SimpleDateFormat
	 * @throws ParseException
	 */
	public static final Date convertStringToDate(String aMask, String strDate) throws ParseException {
		SimpleDateFormat df = null;
		Date date = null;
		df = new SimpleDateFormat(aMask);

		if (log.isDebugEnabled()) {
			log.debug("converting '" + strDate + "' to date with mask '" + aMask + "'");
		}

		try {
			date = df.parse(strDate);
		} catch (ParseException pe) {
			// log.error("ParseException: " + pe);
			throw new ParseException(pe.getMessage(), pe.getErrorOffset());
		}

		return (date);
	}

	public static String getTime() {
		return getDateTime("yyyyMMddHHmmsss", Calendar.getInstance().getTime());
	}

	public static String getDateTime() {
		return getDateTime("yyyyMMdd", Calendar.getInstance().getTime());
	}

	public static final String getDateTimeFull() {
		SimpleDateFormat df = null;
		String returnValue = "";
		Date aDate = new Date();
		df = new SimpleDateFormat(timesecondPattern);
		returnValue = df.format(aDate);
		return (returnValue);
	}

	public static final String getDateTimeFullNoSplit() {
		SimpleDateFormat df = null;
		String returnValue = "";
		Date aDate = new Date();
		df = new SimpleDateFormat(timesecondPatterns);
		returnValue = df.format(aDate);
		return (returnValue);
	}

	// 比较两个时间是否相等
	public static boolean isEqual(Date d1, Date d2) {
		if (d1 == null && d2 == null) {
			return true;
		} else if (d1 != null && d2 != null) {
			if (getFormatDate(d1, defaultDateDB).equals(getFormatDate(d2, defaultDateDB))) {
				return true;
			}
		}
		return false;
	}

	// 年份相减
	public static int tractYear(Date date, Date date1) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy");
		return Integer.parseInt(format.format(date1)) - Integer.parseInt(format.format(date));
	}

	public static int getYear(Date date) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy");
		return Integer.parseInt(format.format(date));
	}
	/** 
     * 得到本季度最后一天的日期 
     * @Methods Name getLastDayOfQuarter 
     * @return Date 
     */  
	public static Date getLastDayOfQuarter(Date date)   {     
        Calendar cDay = Calendar.getInstance();     
        cDay.setTime(date);  
        int curMonth = cDay.get(Calendar.MONTH);  
        if (curMonth >= Calendar.JANUARY && curMonth <= Calendar.MARCH){    
            cDay.set(Calendar.MONTH, Calendar.MARCH);  
        }  
        if (curMonth >= Calendar.APRIL && curMonth <= Calendar.JUNE){    
            cDay.set(Calendar.MONTH, Calendar.JUNE);  
        }  
        if (curMonth >= Calendar.JULY && curMonth <= Calendar.AUGUST) {    
            cDay.set(Calendar.MONTH, Calendar.AUGUST);  
        }  
        if (curMonth >= Calendar.OCTOBER && curMonth <= Calendar.DECEMBER) {    
            cDay.set(Calendar.MONTH, Calendar.DECEMBER);  
        }  
        cDay.set(Calendar.DAY_OF_MONTH, cDay.getActualMaximum(Calendar.DAY_OF_MONTH));  
        System.out.println(cDay.getTime());  
        return cDay.getTime();     
    } 
	/** 
     * 得到本季度第一天的日期 
     * @Methods Name getFirstDayOfQuarter 
     * @return Date 
     */  
    public static Date getFirstDayOfQuarter(Date date)   {     
        Calendar cDay = Calendar.getInstance();     
        cDay.setTime(date);  
        int curMonth = cDay.get(Calendar.MONTH);  
        if (curMonth >= Calendar.JANUARY && curMonth <= Calendar.MARCH){    
            cDay.set(Calendar.MONTH, Calendar.JANUARY);  
        }  
        if (curMonth >= Calendar.APRIL && curMonth <= Calendar.JUNE){    
            cDay.set(Calendar.MONTH, Calendar.APRIL);  
        }  
        if (curMonth >= Calendar.JULY && curMonth <= Calendar.AUGUST) {    
            cDay.set(Calendar.MONTH, Calendar.JULY);  
        }  
        if (curMonth >= Calendar.OCTOBER && curMonth <= Calendar.DECEMBER) {    
            cDay.set(Calendar.MONTH, Calendar.OCTOBER);  
        }  
        cDay.set(Calendar.DAY_OF_MONTH, cDay.getActualMinimum(Calendar.DAY_OF_MONTH));  
        System.out.println(cDay.getTime());  
        return cDay.getTime();     
    }
    /** 
     * 得到本月第一天的日期 
     * @Methods Name getFirstDayOfMonth 
     * @return Date 
     */  
    public static Date getFirstDayOfMonth(Date date)   {     
        Calendar cDay = Calendar.getInstance();     
        cDay.setTime(date);  
        cDay.set(Calendar.DAY_OF_MONTH, 1);  
        System.out.println(cDay.getTime());  
        return cDay.getTime();     
    }     
    /** 
     * 得到本月最后一天的日期 
     * @Methods Name getLastDayOfMonth 
     * @return Date 
     */  
    public static Date getLastDayOfMonth(Date date)   {     
        Calendar cDay = Calendar.getInstance();     
        cDay.setTime(date);  
        cDay.set(Calendar.DAY_OF_MONTH, cDay.getActualMaximum(Calendar.DAY_OF_MONTH));  
        System.out.println(cDay.getTime());  
        return cDay.getTime();     
    } 
    /**
	 * 获取某年第一天日期
	 * @param year 年份
	 * @return Date
	 */
	public  static Date getYearFirst(int year){
		Calendar calendar = Calendar.getInstance();
		calendar.clear();
		calendar.set(Calendar.YEAR, year);
		Date currYearFirst = calendar.getTime();
		return currYearFirst;
	}
	
	/**
	 * 获取某年最后一天日期
	 * @param year 年份
	 * @return Date
	 */
	public static Date getYearLast(int year){
		Calendar calendar = Calendar.getInstance();
		calendar.clear();
		calendar.set(Calendar.YEAR, year);
		calendar.roll(Calendar.DAY_OF_YEAR, -1);
		Date currYearLast = calendar.getTime();
		
		return currYearLast;
	}
	
	
	/**
	 * 判断当前日期是否大于5月1日
	 * @return
	 */				
	public static boolean compareTo51(){
		String curdate = getSimpleFormatDate(new Date());
		String date51 = curdate.substring(0,5)+"5-1";
		 int i = dateCompare(curdate, date51, "yyyy-MM-dd");
		 boolean flag = false;
		 if(i>=0){
			 flag = true;
		 }
		 return flag;
	}


}
